<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<!-- 使用Js实现输入验证 -->
		<style type="text/css">
			.grid{
				width:400px;
				border-collapse: collapse;
			}
			
			.grid th,td{
				border:solid 1px aliceblue;
			}
			
			.grid th{
				text-align: right;
				background: orange;
				color:#FFF;
				height: 26px;
			}
			
			.err{
				border:solid 1px red;
			}
		</style>
	</head>
	<body>
		<!-- 
			return validForm()
				当validForm()的返回值为false时，数据将不会被提交
				当validForm()的返回值为true时，数据将会被提交处理
		-->
		<form id="addForm" name="addForm" action="add.do" onsubmit="return validForm();">
			<table class="grid">
				<tr>
					<th>姓名：</th>
					<td>
						<input id="userName" name="userName" />						
					</td>
				</tr>
				<tr>
					<th>年龄：</th>
					<td>
						<input id="age"  />
					</td>
				</tr>
				<tr>
					<th>性别：</th>
					<td>
						<input type="radio" name="gender" id="gender_man" value="1" />
						<label for="gender_man">男</label>
						<input type="radio" name="gender" id="gender_girl" value="0" />
						<label for="gender_girl">女</label>
					</td>
				</tr>
				<tr>
					<th>学历：</th>
					<td>
						<select id="grade">
							<option value="0">---请选择---</option>
							<option value="1">高中</option>
							<option value="2">大学</option>
							<option value="3">硕士</option>
							<option value="4">博士</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>联系电话：</th>
					<td>
						<input id="tel" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="保存" />
						<input type="reset" value="重置" />
					</td>
				</tr>
			</table>
		</form>
	</body>
	
	<script type="text/javascript">
		function validForm(){
			var result = true;
			//按Id获取元素对象的值
			var obj_name =document.getElementById("userName");
			//判断字符串是否为空
			if(obj_name.value=='' || obj_name.value.length==0){
				obj_name.setAttribute("class","err");
				result = false;
			}
			else{
				obj_name.removeAttribute("class");
			}
			
			var age = document.getElementById("age").value;
			if(age=='' || age.length==0){
				document.getElementById("age").setAttribute("class","err");	
				result = false;
			}
			else{
				document.getElementById("age").removeAttribute("class");
			}
			
			/*
			//获取form对象
			var form = document.getElementById("addForm");
			console.log("form = " + form);
			//通过name属性获取一个表单元素对象的值
			console.log(form.userName.value)
			*/
			return result;
		}
		
	</script>
</html>
